package com.atstudy.headline.web.admin.controller.advertisement.adCampaigns;

import com.atstudy.headline.entity.AdCampaigns;
import com.atstudy.headline.entity.AdCreatives;
import com.atstudy.headline.entity.Advertisers;
import com.atstudy.headline.enums.BaseStatus;
import com.atstudy.headline.result.Result;
import com.atstudy.headline.web.admin.service.AdCampaignsService;
import com.atstudy.headline.web.admin.service.AdCreativesService;
import com.atstudy.headline.web.admin.vo.ad.AdCampaignsVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/admin/adCampaigns")
public class adCampaignsController {

    @Autowired()
    private AdCampaignsService campaignsService;

    @Autowired
    private AdCreativesService adCreativesService;


    @RequestMapping("/page")
    public Result<IPage<AdCampaigns>> pageAdInfo(@RequestParam Integer current,
                                                 @RequestParam Integer size,
                                                 AdCampaignsVo adCampaigns){
        Page<AdCampaigns> page = new Page<>(current,size);
        LambdaQueryWrapper<AdCampaigns> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like( adCampaigns.getCampaignName()!=null,AdCampaigns::getCampaignName,adCampaigns.getCampaignName());
        queryWrapper.like( adCampaigns.getCompanyName()!=null,AdCampaigns::getCompanyName,adCampaigns.getCompanyName());
        queryWrapper.eq( adCampaigns.getStatus()!=null,AdCampaigns::getStatus,adCampaigns.getStatus() );
        IPage<AdCampaigns> campaignsIPage =campaignsService.pageInfoByAdCampaigns(page,adCampaigns);
        return Result.ok(campaignsIPage);
    }

    /**
     * 增加/修改
     * @param adCampaigns
     * @return
     */
    @PostMapping("/saveOrUpdate")
    public Result saveOrUpdate(@RequestBody AdCampaigns adCampaigns){
        campaignsService.saveOrUpdate(adCampaigns);
        return Result.ok();
    }

    /**
     * 删除广告计划（同时删除关联广告创意）
     * @param campaignId
     * @return
     */
    @DeleteMapping("/delete")
    @Transactional
    public Result delete(@RequestParam Integer campaignId) {
        // 1. 检查广告计划是否存在
        AdCampaigns campaign = campaignsService.getById(campaignId);
        if (campaign == null) {
            return Result.fail(404, "广告计划不存在");
        }

        // 2. 删除该广告计划下的所有广告创意
        adCreativesService.deleteByCampaignId(campaignId);

        // 3. 删除广告计划
        campaignsService.removeById(campaignId);

        return Result.ok();
    }

    /**
     * 根据campaignId改变状态
     * @param campaignId
     * @param status
     * @return
     */
    @PostMapping("/updateStatus")
    @Transactional // 声明式事务管理，确保操作一致性
    public Result updateStatus(@RequestParam Integer campaignId, @RequestParam Integer status) {
        // 1. 查询原始广告计划状态
        AdCampaigns campaign = campaignsService.getById(campaignId);
        if (campaign == null) {
            return Result.fail(201, "广告计划不存在");
        }

        // 2. 判断是否需要级联暂停广告创意
        boolean needSuspendCreatives = campaign.getStatus() != status && status == 4; // 4表示暂停状态

        // 3. 更新广告计划状态
        LambdaUpdateWrapper<AdCampaigns> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(AdCampaigns::getCampaignId, campaignId);
        updateWrapper.set(AdCampaigns::getStatus, status);
        boolean updateResult = campaignsService.update(updateWrapper);

        if (!updateResult) {
            return Result.fail(201, "广告计划状态更新失败");
        }

        // 4. 当广告计划被暂停时，级联暂停所有广告创意
        if (needSuspendCreatives) {
            suspendCampaignCreatives(campaignId);
        }

        return Result.ok();
    }

    /**
     * 暂停广告计划下的所有广告创意
     */
    private void suspendCampaignCreatives(Integer campaignId) {
        // 查询广告计划下的所有广告创意
        List<AdCreatives> creatives = adCreativesService.list(
                Wrappers.<AdCreatives>lambdaQuery()
                        .eq(AdCreatives::getCampaignId, campaignId)
                        .eq(AdCreatives::getStatus, 1) // 仅暂停启用状态的创意（假设1表示启用）
        );

        if (creatives.isEmpty()) {
            return;
        }

        // 批量更新广告创意状态为"禁用"（0表示禁用）
        List<Integer> creativeIds = creatives.stream()
                .map(AdCreatives::getCreativeId)
                .collect(Collectors.toList());

        LambdaUpdateWrapper<AdCreatives> creativeUpdateWrapper = new LambdaUpdateWrapper<>();
        creativeUpdateWrapper.in(AdCreatives::getCreativeId, creativeIds);
        creativeUpdateWrapper.set(AdCreatives::getStatus, 0); // 0表示禁用状态

        adCreativesService.update(creativeUpdateWrapper);
    }

    /**
     * 查询广告计划id和广告计划名称
     * @return
     */
    @GetMapping("/dropdown")
    public Result<List<Map<Integer, Object>>> getCampaign() {
        List<Map<Integer, Object>> dropdownList = campaignsService.selectCampaigns();
        return Result.ok(dropdownList);
    }
}
